package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    @Transactional
    public R submit(@RequestBody Orders orders){
        Long userId = BaseContext.getCurrentId();
        //A. 获得当前用户id, 查询当前用户的购物车数据
        //select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(qw);
        if (shoppingCarts==null||shoppingCarts.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }

        //B. 根据当前登录用户id, 查询用户数据
        //select * from user where id = ?
        User user = userService.getById(userId);

        //C. 根据地址ID, 查询地址数据
        //select * from address_book where id = ?
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook==null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        long orderId = IdWorker.getId();//订单号
        BigDecimal amount = new BigDecimal(0);//总价
        //D. 组装订单明细数据, 批量保存订单明细
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart,orderDetail);
            orderDetail.setNumber(shoppingCart.getNumber());

            orderDetail.setOrderId(orderId);

            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount=amount.add(orderDetail.getAmount());
            orderDetailService.save(orderDetail);
        }

        //E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(amount);
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setNumber(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());

        orders.setAddress(
                (addressBook.getProvinceName()) ==null?"":addressBook.getProvinceName()+
                (addressBook.getCityName()==null?"":addressBook.getCityName())+
                (addressBook.getDistrictName()==null?"":addressBook.getDistrictName())+
                (addressBook.getDetail()==null?"":addressBook.getDetail())
        );

        ordersService.save(orders);

        //F. 删除当前用户的购物车列表数据
        LambdaQueryWrapper<ShoppingCart> qw1=new LambdaQueryWrapper<>();
        qw1.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(qw1);
        return R.success("下单成功");
    }

    //分页
    @GetMapping("/userPage")
    public R userPage(Integer page, Integer pageSize){
        IPage<Orders> pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> qw=new LambdaQueryWrapper<>();
        qw.eq(Orders::getUserId,BaseContext.getCurrentId());
        ordersService.page(pageInfo,qw);

        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> ordersDtos=new ArrayList<>();
        for (Orders order : records) {
            Long addressBookId = order.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);
            String consignee = addressBook.getConsignee();
            String phone = addressBook.getPhone();
            String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();

            Long userId = order.getUserId();
            LambdaQueryWrapper<User> qw2=new LambdaQueryWrapper<>();
            qw2.eq(userId!=null,User::getId,userId);
            User user = userService.getOne(qw2);
            String userName = user.getName();

            Long id = order.getId();
            LambdaQueryWrapper<OrderDetail> qw1=new LambdaQueryWrapper<>();
            qw1.eq(id!=null,OrderDetail::getOrderId,id);
            List<OrderDetail> orderDetails = orderDetailService.list(qw1);

            OrdersDto ordersDto = new OrdersDto();
            BeanUtil.copyProperties(order,ordersDto);
            ordersDto.setConsignee(consignee);
            ordersDto.setPhone(phone);
            ordersDto.setAddress(address);
            ordersDto.setUserName(userName);
            ordersDto.setOrderDetails(orderDetails);

            ordersDtos.add(ordersDto);
        }

        Map<String,Object> data = new HashMap();
        data.put("records",ordersDtos);

        return R.success(data);
    }

























}
